package com.xinqi.common.core.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 分数格式化工具（1.123 -> 1.1）
 *
 * @author linkai
 * @date 2023/8/14
 */
public class ScoreJacksonSerialize extends JsonSerializer<BigDecimal> {

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            return;
        }
        // 将BigDecimal字段格式化为一位小数
        gen.writeString(value.setScale(1, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
    }
}
